package com.hzsai.mininote.interceptor;

import com.hzsai.mininote.common.ResponseRe;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author hzsai
 * @date 2020/1/9 13:13
 * @usage:
 * 全局controller异常捕获类
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionInterceptor {

    private static final int ZERO = 0;

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseRe validateExceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception e) {
        String message = "unknown error";

        if (e instanceof MethodArgumentNotValidException) {
            message = ((MethodArgumentNotValidException) e).getBindingResult().getFieldError().getDefaultMessage();
            return ResponseRe.fail(400, message, null);
        }
        return ResponseRe.fail(400, message, null);
    }
}
